import { Component } from '@angular/core';
import { NavController, NavParams, LoadingController, ToastController, ModalController } from 'ionic-angular';
import { BaseUI } from '../../common/baseui';
import { RestProvider } from '../../providers/rest/rest';
import { Storage } from '@ionic/storage';
import { AnswerPage } from '../answer/answer';

/**
 * Generated class for the DetailsPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */


@Component({
  selector: 'page-details',
  templateUrl: 'details.html',
})
export class DetailsPage extends BaseUI {
  id: string;
  question: string[];
  anwsers: any[];
  errorMessage: any;
  isFavourite: boolean;
  userId: string;
  isMyQuestion: boolean; //我自己回答
  constructor(
    public navCtrl: NavController,
    public navParams: NavParams,
    private loadingCtrl: LoadingController,
    private toastCtrl: ToastController,
    private rest: RestProvider,
    private storage: Storage,
    private modalCtrl: ModalController) {
    super();
    this.id = this.navParams.get('id');
  }

  ionViewDidLoad() {
    this.loadQuestion(this.id);
  }
  loadQuestion(id) {
    this.storage.get('UserId').then((val) => {
      this.userId = val;
      if (val != null) {
        var loading = super.showLoading(this.loadingCtrl, "加载中...");
        this.rest.getQuestionWidthUser(id, val)
          .subscribe(data => {
            this.question = data;
            this.anwsers = data['Answers'];
            this.isFavourite = data['IsFavourite'];
            this.isMyQuestion = (data['OwnUserId'] === val);
          }, error => this.errorMessage = <any>error);
      }
    });
  }
  saveFavourite() {
    var loading = super.showLoading(this.loadingCtrl, "请求中...");
    this.rest.saveFavourite(this.id, this.userId)
      .subscribe(data => {
        if (data["Status"] == "OK") {
          loading.dismiss();
          super.showToast(this.toastCtrl, this.isFavourite ? "取消关注成功" : "关注问题成功");
          this.isFavourite = !this.isFavourite;
        }
      }, error => this.errorMessage = <any>error);
  }
  goAnwser() {
    let modal = this.modalCtrl.create(AnswerPage, {
      "id": this.id
    })
    modal.onDidDismiss(()=>{
      this.loadQuestion(this.id);
    })
    modal.present();
  }
}
